package com.quanquan.store.service.marketActivity;

import DTO.PageDTO;
import com.alibaba.fastjson.JSON;
import com.quanquan.store.dto.StoreDTO;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCard;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardChance;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardGift;
import com.quanquan.store.entity.marketActivity.scratchCard.ScratchCardRecord;
import com.quanquan.store.repository.marketActivity.scratchCard.ScratchCardChanceRepository;
import com.quanquan.store.repository.marketActivity.scratchCard.ScratchCardGiftRepository;
import com.quanquan.store.repository.marketActivity.scratchCard.ScratchCardRecordRepository;
import com.quanquan.store.repository.marketActivity.scratchCard.ScratchCardRepository;
import com.quanquan.store.request.marketActivity.ScratchCardRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import utils.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName ScratchCardService
 * @Description
 * @Author Owen
 * @Date 2019/8/27 0027 下午 4:27
 * @Version V1.0
 **/

@Service
public class ScratchCardService {

    @Autowired
    private ScratchCardRepository scratchCardRepository;

    @Autowired
    private ScratchCardChanceRepository scratchCardChanceRepository;

    @Autowired
    private ScratchCardGiftRepository scratchCardGiftRepository;

    @Autowired
    private ScratchCardRecordRepository scratchCardRecordRepository;

    /**
     * 根据ID查询活动信息
     * @param id
     * @return
     */
    public ScratchCard getById(Long id){
        ScratchCard scratchCard = scratchCardRepository.findById(id).orElse(null);
        return scratchCard;
    }

    public ScratchCard saveOrUpdate(ScratchCard scratchCard){
        return scratchCardRepository.saveAndFlush(scratchCard);
    }

    /**
     * 根据活动id和用户id获取活动次数信息
     * @param scratchCardId
     * @param userId
     * @return
     */
    public ScratchCardChance getByIdAndUserId(Long scratchCardId,String userId){
        ScratchCardChance scratchCardChance = new ScratchCardChance();
        scratchCardChance.setUserId(userId);
        scratchCardChance.setScratchCardId(scratchCardId);
        Example<ScratchCardChance> example = Example.of(scratchCardChance);
        scratchCardChance = scratchCardChanceRepository.findOne(example).orElse(null);
        return scratchCardChance;
    }

    /**
     * 保存或修改用户活动次数信息
     * @param scratchCardChance
     * @return
     */
    public ScratchCardChance saveOrUpdate(ScratchCardChance scratchCardChance){
        return scratchCardChanceRepository.saveAndFlush(scratchCardChance);
    }


    /**
     * 根据活动id获取活动所有有效奖项
     * @param scratchCardId
     * @return
     */
    public List<ScratchCardGift> getGiftList(Long scratchCardId){
        List<ScratchCardGift> scratchCardGifts = scratchCardGiftRepository.findScratchCardGift(scratchCardId);
        return scratchCardGifts;
    }

    /**
     * 根据活动id获取活动所有有效奖项总概率
     * @param scratchCardId
     * @return
     */
    public Integer sumGiftOdds(Long scratchCardId){
        Integer sumGiftOdds = scratchCardGiftRepository.sumGiftOdds(scratchCardId);
        return sumGiftOdds;
    }

    /**
     * 保存或修改活动参与记录
     * @param scratchCardRecord
     * @return
     */
    public ScratchCardRecord saveOrUpdate(ScratchCardRecord scratchCardRecord){
        scratchCardRecord = scratchCardRecordRepository.saveAndFlush(scratchCardRecord);
        return scratchCardRecord;
    }

    /**
     * 扣将活动奖项剩余库存
     * @param giftId
     * @return
     */
    public int substractGiftStock(Long giftId){
        int stock = scratchCardGiftRepository.substractStock(giftId);
        return stock;
    }

    /**
     * 根据奖项ID获取奖项信息
     * @param giftId
     * @return
     */
    public ScratchCardGift getGiftById(Long giftId){
        ScratchCardGift scratchCardGift = scratchCardGiftRepository.findById(giftId).orElse(null);
        return scratchCardGift;
    }

    /**
     * 添加或更新奖项信息
     * @param scratchCardGift
     * @return
     */
    public ScratchCardGift saveOrUpdate(ScratchCardGift scratchCardGift){
        scratchCardGift = scratchCardGiftRepository.saveAndFlush(scratchCardGift);
        return scratchCardGift;
    }

    /**
     * 获取用户活动奖品列表
     * @param scratchCardId
     * @param userId
     * @return
     */
    public List<ScratchCardRecord> getRecordList(Long scratchCardId,String userId){
        return scratchCardRecordRepository.findUserRecordList(scratchCardId,userId);
    }

    /**
     * 管理后台获取所有刮刮卡活动列表
     * @param request
     * @return
     */
    public PageDTO findAllScratchCardByPage(ScratchCardRequest request){
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(request.getPage(),request.getSize(),sort);

        Page<ScratchCard> all = scratchCardRepository.findAll((Specification<ScratchCard>) (root, query, criteriaBuilder)->{
            Predicate conditions = criteriaBuilder.conjunction();
            conditions = criteriaBuilder.and(criteriaBuilder.notEqual(root.get("status").as(Integer.class),2));
            if(StringUtils.isNotEmpty(request.getKeywords())){
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + request.getKeywords() + "%");
                conditions = criteriaBuilder.and(conditions,p1);
            }
            return query.where(conditions).getRestriction();
        }, pageable);
        PageDTO<ScratchCard> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());
        pageDTO.setList(all.getContent());
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(request.getPage());
        pageDTO.setPageSize(request.getSize());
        pageDTO.setKeyword(request.getKeywords());
        return pageDTO;
    }

    /**
     * 后台获取活动所有奖项
     * @param request
     * @return
     */
    public PageDTO getAllScratchGifts(ScratchCardRequest request){
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(request.getPage(),request.getSize(),sort);

        System.out.println(JSON.toJSONString(request));
        Page<ScratchCardGift> all = scratchCardGiftRepository.findAll((Specification<ScratchCardGift>) (root, query, criteriaBuilder)->{
            Predicate conditions = criteriaBuilder.conjunction();
            conditions = criteriaBuilder.and(criteriaBuilder.equal(root.get("scratchCardId").as(Long.class),request.getId()));
            conditions = criteriaBuilder.and(conditions,criteriaBuilder.notEqual(root.get("status").as(Integer.class),2));
            return query.where(conditions).getRestriction();
        }, pageable);
        PageDTO<ScratchCardGift> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());
        pageDTO.setList(all.getContent());
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(request.getPage());
        pageDTO.setPageSize(request.getSize());
        pageDTO.setKeyword(request.getKeywords());
        return pageDTO;
    }


    /**
     * 后台获取所有活动记录
     * @param request
     * @return
     */
    public PageDTO getAllScratchRecords(ScratchCardRequest request){
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(request.getPage(),request.getSize(),sort);

        Page<ScratchCardRecord> all = scratchCardRecordRepository.findAll((Specification<ScratchCardRecord>) (root, query, criteriaBuilder)->{
            Predicate conditions = criteriaBuilder.conjunction();
            conditions = criteriaBuilder.and(criteriaBuilder.equal(root.get("scratchCardId").as(Long.class),request.getId()));
            return query.where(conditions).getRestriction();
        }, pageable);
        PageDTO<ScratchCardRecord> pageDTO = new PageDTO<>();
        pageDTO.setTotal(all.getTotalElements());
        pageDTO.setList(all.getContent());
        pageDTO.setTotalPage(all.getTotalPages());
        pageDTO.setPage(request.getPage());
        pageDTO.setPageSize(request.getSize());
        pageDTO.setKeyword(request.getKeywords());
        return pageDTO;
    }
}
